#include "StdAfx.h"
#include "adapterInfo.h"

adapterInfo::adapterInfo(void)
{
}


adapterInfo::~adapterInfo(void)
{
}
std::vector<MyAdapterInfo>& adapterInfo::get_all_adapters(){
	{
		std::vector<MyAdapterInfo> temp;
		_allAdapters.swap(temp);
	}
	PIP_ADAPTER_INFO pAdapterInfo; 
	DWORD dwRetVal=0;
	HANDLE   hMprConfig;   
	std::string   strInfo,strTmp;   
	PIP_INTERFACE_INFO   plfTable=NULL;   
	IP_ADAPTER_INDEX_MAP   AdaptMap;   
	DWORD   dwBufferSize=0;   
	WCHAR   szFriendName[256];   
	DWORD   tchSize=sizeof(WCHAR)*256;   
	ZeroMemory(&szFriendName,tchSize);   
	dwRetVal=MprConfigServerConnect(NULL,&hMprConfig);   
	dwRetVal=GetInterfaceInfo(NULL,&dwBufferSize);   
	if(dwRetVal==ERROR_INSUFFICIENT_BUFFER)   
	{   
		plfTable=(PIP_INTERFACE_INFO)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,dwBufferSize);   
		GetInterfaceInfo(plfTable,&dwBufferSize);   
	}   
	ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO); 
	pAdapterInfo = (PIP_ADAPTER_INFO)malloc(ulOutBufLen); 
	dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen);
	if (dwRetVal == ERROR_BUFFER_OVERFLOW) { 
		free(pAdapterInfo); 
		pAdapterInfo  = NULL;
		pAdapterInfo  = (PIP_ADAPTER_INFO)malloc(ulOutBufLen); 
		dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen);
	} 
	if (dwRetVal == NO_ERROR){ 
		PIP_ADAPTER_INFO pAdapter = pAdapterInfo;
		while (pAdapter) { 
			if(pAdapter->Type == MIB_IF_TYPE_ETHERNET){

				MyAdapterInfo info;
				memset(&info,0,sizeof(MyAdapterInfo));
				memcpy(info.AdapterName,pAdapter->AdapterName,260);
				memcpy(info.Description,pAdapter->Description,132);
				memcpy(info.ipaddress,pAdapter->IpAddressList.IpAddress.String,16);
				std::string adapterName=pAdapter->AdapterName;
				adapterName.insert(0,"\\DEVICE\\TCPIP_");
				WCHAR wszName[256];
				memset( wszName, 0, 256 );
				int nLen = MultiByteToWideChar( CP_ACP,NULL, adapterName.c_str(),-1,NULL,0);
				MultiByteToWideChar(CP_ACP,NULL,adapterName.c_str(),-1,wszName,nLen);
				dwRetVal=MprConfigGetFriendlyName(hMprConfig,wszName,(PWCHAR)szFriendName,tchSize); 
				char szName[256];
				memset( szName, 0, 256 );
				nLen = WideCharToMultiByte( CP_ACP,NULL, szFriendName,-1,NULL,0,NULL,FALSE );
				WideCharToMultiByte (CP_ACP,NULL,szFriendName,-1,szName,nLen,NULL,FALSE);
				memcpy(info.lanFriendName,szName,256);
				_allAdapters.push_back(info);
			}
			pAdapter = pAdapter->Next; 
		}
	} 
	if (pAdapterInfo != NULL){
		free(pAdapterInfo);
	}
	return _allAdapters;
}
std::string adapterInfo::get_sel_adapter(int index){
	if(index>=0&&index<_allAdapters.size()){
		std::string strret;
		//strret=_allAdapters[index].ipaddress;
		strret=_allAdapters[index].AdapterName;
		strret.insert(0,"\\Device\\NPF_");
		return strret;
	}
	else{
		return "";
	}
	return 0;
}